package com.example.starter.security.configure;

import cn.hutool.core.util.ArrayUtil;
import com.example.starter.security.handler.ExampleAuthenticationEntryPoint;
import lombok.RequiredArgsConstructor;
import lombok.SneakyThrows;
import org.springframework.security.config.annotation.web.builders.HttpSecurity;
import org.springframework.security.oauth2.config.annotation.web.configuration.EnableResourceServer;
import org.springframework.security.oauth2.config.annotation.web.configuration.ResourceServerConfigurerAdapter;
import org.springframework.security.oauth2.config.annotation.web.configurers.ResourceServerSecurityConfigurer;
import org.springframework.security.oauth2.provider.token.DefaultTokenServices;
import org.springframework.security.oauth2.provider.token.TokenStore;

/**
 * @author 王令
 * @since 2022/8/9 21:06
 */
@EnableResourceServer
@RequiredArgsConstructor
public class OAuth2ResourceConfiguration extends ResourceServerConfigurerAdapter {

    private final SecurityProperties properties;
    private final TokenStore tokenStore;

    @SneakyThrows
    @Override
    public void configure(HttpSecurity http) {
        http
                .authorizeRequests()
                .antMatchers(ArrayUtil.toArray(properties.getPermitUrls(), String.class)).permitAll()
                .anyRequest().authenticated();
    }

    @SneakyThrows
    @Override
    public void configure(ResourceServerSecurityConfigurer resources) {
        resources.tokenServices(tokenServices())
                .authenticationEntryPoint(new ExampleAuthenticationEntryPoint());
    }

    public DefaultTokenServices tokenServices() {
        DefaultTokenServices tokenServices = new DefaultTokenServices();
        tokenServices.setTokenStore(tokenStore);
        return tokenServices;
    }

}
